<template>
  <view class="page">
    <view v-if="!book" class="loading">加载中...</view>
    <view v-else class="detail">
      <image :src="book.cover || '/static/img/default-item.png'" class="cover" mode="aspectFill"></image>
      <view class="meta">
        <text class="title">{{ book.name }}</text>
        <view class="rating" v-if="book.rating">
          <text class="rating-value">{{ book.rating }}</text>
          <text class="rating-count">({{ book.rating_count }}人评分)</text>
        </view>
        <text class="author">作者：{{ book.author || '未知' }}</text>
        <text class="info" v-if="book.translator">译者：{{ book.translator }}</text>
        <text class="info" v-if="book.publisher">出版社：{{ book.publisher }}</text>
        <text class="info" v-if="book.publish_date">出版日期：{{ book.publish_date }}</text>
        <text class="info" v-if="book.isbn">ISBN：{{ book.isbn }}</text>
        <text class="info" v-if="book.pages">页数：{{ book.pages }}</text>
        <text class="info" v-if="book.binding">装帧：{{ book.binding }}</text>
        <text class="category" v-if="book.category">分类：{{ book.category }}</text>
        <view class="stock-info">
          <text class="stock-label">库存：</text>
          <text :class="['stock-value', book.stock > 0 ? 'in-stock' : 'out-stock']">
            {{ book.stock > 0 ? book.stock + ' 本' : '无库存' }}
          </text>
        </view>
        <text class="price" v-if="book.price">价格：￥{{ book.price }}</text>
      </view>
      
      <view class="section" v-if="book.summary">
        <text class="section-title">内容简介</text>
        <text class="section-content">{{ book.summary }}</text>
      </view>
      
      <view class="section" v-if="book.author_intro">
        <text class="section-title">作者简介</text>
        <text class="section-content">{{ book.author_intro }}</text>
      </view>
      
      <view class="actions">
        <button class="btn" @click="addToBookshelf">加入书架</button>
        <button class="btn" @click="addToCart" v-if="book.stock > 0">加入借书车</button>
        <button class="btn primary" @click="borrowNow" v-if="book.stock > 0">
          立即借阅
        </button>
        <!-- 新增：预约功能 -->
        <button class="btn reserve" @click="handleReserve" v-if="book.stock === 0 && !isReserved">
          预约图书
        </button>
        <button class="btn reserved" v-if="isReserved" disabled>
          已预约
        </button>
        <text class="out-stock-tip" v-if="book.stock === 0">
          图书暂无库存，您可以预约此书，有人归还时会第一时间通知您
        </text>
      </view>
    </view>
  </view>
</template>

<script>
import { myRequest } from '@/util/request.js';

export default {
  name: 'BookInfo',
  data() {
    return {
      id: '',
      book: null,
      isReserved: false // 是否已预约此书
    };
  },
  onLoad(query) {
    this.id = query?.id || '';
    this.fetchDetail();
    this.checkReservationStatus();
  },
  methods: {
    async fetchDetail() {
      if (!this.id) return;
      try {
        const data = await myRequest({ url: `/api/books/${this.id}`, method: 'GET' });
        this.book = data;
      } catch (e) {
        console.error('获取详情失败', e);
        uni.showToast({ title: '获取图书详情失败', icon: 'none' });
      }
    },
    async addToBookshelf() {
      try {
        await myRequest({ url: '/api/bookshelf', method: 'POST', data: { bookId: Number(this.id) } });
        uni.showToast({ title: '已加入书架', icon: 'success' });
      } catch (e) {
        console.error('加入书架失败', e);
      }
    },
    async addToCart() {
      try {
        await myRequest({ url: '/api/cart', method: 'POST', data: { bookId: Number(this.id), borrowDays: 14 } });
        uni.showToast({ title: '已加入借书车', icon: 'success' });
      } catch (e) {
        console.error('加入借书车失败', e);
      }
    },
    async borrowNow() {
      if (this.book.stock <= 0) {
        uni.showToast({ title: '暂无库存', icon: 'none' });
        return;
      }
      
      uni.showModal({
        title: '确认借阅',
        content: `确定要借阅《${this.book.name}》吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              await myRequest({ 
                url: '/api/borrow', 
                method: 'POST', 
                data: { bookId: Number(this.id), borrowDays: 30 } 
              });
              uni.showToast({ title: '借阅成功', icon: 'success' });
              // 刷新图书信息
              setTimeout(() => {
                this.fetchDetail();
              }, 1000);
            } catch (e) {
              console.error('借阅失败', e);
            }
          }
        }
      });
    },

    // 新增：预约功能
    async handleReserve() {
      uni.showModal({
        title: '确认预约',
        content: `确定要预约《${this.book.name}》吗？图书可借时我们会第一时间通知您。`,
        success: async (res) => {
          if (res.confirm) {
            try {
              await myRequest({
                url: '/api/reservations',
                method: 'POST',
                data: { bookId: Number(this.id) }
              });
              uni.showToast({ title: '预约成功', icon: 'success' });
              this.isReserved = true;
            } catch (e) {
              console.error('预约失败', e);
              uni.showToast({ title: e.message || '预约失败', icon: 'none' });
            }
          }
        }
      });
    },

    // 新增：检查预约状态
    async checkReservationStatus() {
      try {
        const data = await myRequest({
          url: '/api/reservations/my-reservations',
          method: 'GET',
          data: { status: 'waiting,available' }
        });
        // 检查是否已预约此书
        this.isReserved = data.some(reservation => 
          reservation.book_id === Number(this.id) && 
          ['waiting', 'available'].includes(reservation.status)
        );
      } catch (e) {
        console.error('检查预约状态失败', e);
      }
    }
  }
}
</script>

<style scoped>
.page { padding: 20rpx; background: #f5f5f5; min-height: 100vh; }
.loading { text-align: center; color: #999; padding: 60rpx 0; }
.detail { display: flex; flex-direction: column; gap: 20rpx; }
.cover { width: 100%; height: 500rpx; border-radius: 12rpx; background: #fff; }
.meta { display: flex; flex-direction: column; gap: 10rpx; background: #fff; border-radius: 12rpx; padding: 20rpx; }
.title { font-size: 36rpx; color: #333; font-weight: 700; line-height: 1.4; }
.rating { display: flex; align-items: center; gap: 10rpx; margin: 10rpx 0; }
.rating-value { font-size: 32rpx; color: #ff9900; font-weight: 700; }
.rating-count { font-size: 24rpx; color: #999; }
.author { font-size: 28rpx; color: #666; margin-top: 10rpx; }
.info { font-size: 26rpx; color: #888; }
.category { font-size: 26rpx; color: #3E88F0; }
.stock-info { display: flex; align-items: center; gap: 10rpx; margin-top: 10rpx; }
.stock-label { font-size: 26rpx; color: #666; }
.stock-value { font-size: 28rpx; font-weight: 700; }
.in-stock { color: #52c41a; }
.out-stock { color: #ff4d4f; }
.price { font-size: 32rpx; color: #ff4d4f; font-weight: 700; margin-top: 10rpx; }

.section { background: #fff; border-radius: 12rpx; padding: 20rpx; }
.section-title { font-size: 30rpx; color: #333; font-weight: 700; display: block; margin-bottom: 10rpx; }
.section-content { font-size: 26rpx; color: #666; line-height: 1.6; display: block; }

.actions { 
  display: flex; 
  gap: 16rpx; 
  position: fixed; 
  bottom: 0; 
  left: 0; 
  right: 0; 
  padding: 20rpx; 
  background: #fff; 
  box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05); 
}
.btn { 
  flex: 1; 
  padding: 20rpx 24rpx; 
  font-size: 28rpx; 
  border-radius: 40rpx; 
  background: #fff; 
  color: #3E88F0; 
  border: 2rpx solid #3E88F0; 
}
.btn.primary { 
  background: #3E88F0; 
  color: #fff; 
  border-color: #3E88F0; 
}
.btn[disabled] {
  opacity: 0.5;
}

/* 新增：预约按钮样式 */
.btn.reserve {
  background: #ff6b35;
  color: #fff;
  border-color: #ff6b35;
}

.btn.reserved {
  background: #d3d3d3;
  color: #999;
  border-color: #d3d3d3;
}

.out-stock-tip {
  position: absolute;
  bottom: -40rpx;
  left: 20rpx;
  right: 20rpx;
  text-align: center;
  font-size: 24rpx;
  color: #666;
  line-height: 1.4;
  background: #fff;
  padding: 10rpx;
  border-radius: 8rpx;
}
</style>

